package com.zwg.git_customview.viewpager2

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import androidx.activity.ComponentActivity
import androidx.recyclerview.widget.RecyclerView
import androidx.viewpager2.widget.ViewPager2
import com.bumptech.glide.Glide
import com.zwg.git_customview.R

/**
 * viewpager2的基本使用
 */
class ViewPager2Activity : ComponentActivity() {

    var mViewPager2: ViewPager2? = null

    var mData: MutableList<String>? = mutableListOf()
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main2)
        initView()
        initData()
    }

    private fun initData() {
//        // 初始化数据
//        mData?.add("https://universal-test-1301203089.file.myqcloud.com/content/7fd2a8377b8401be3d20e65f9e47acb4/1125_15003%E9%A6%96%E9%A1%B5%E4%B8%89%E5%80%8D%E5%9B%BE%E4%B8%80.png")
//        mData?.add("https://img-blog.csdnimg.cn/img_convert/19131443c6b7d54f972d4ad1d938184f.jpeg")
//        mData?.add("https://pic4.zhimg.com/v2-0b4bb3afaeef192ac20e832e7b41e683_r.jpg")
//        mViewPager2?.adapter?.notifyDataSetChanged()
        //设置起始位置
//        mViewPager2?.setCurrentItem(Int.MAX_VALUE / 2)
    }

    private fun initView() {
        // 初始化数据
        mData?.add("https://universal-test-1301203089.file.myqcloud.com/content/7fd2a8377b8401be3d20e65f9e47acb4/1125_15003%E9%A6%96%E9%A1%B5%E4%B8%89%E5%80%8D%E5%9B%BE%E4%B8%80.png")
        mData?.add("https://img-blog.csdnimg.cn/img_convert/19131443c6b7d54f972d4ad1d938184f.jpeg")
        mData?.add("https://pic4.zhimg.com/v2-0b4bb3afaeef192ac20e832e7b41e683_r.jpg")
        mViewPager2 = findViewById(R.id.view_pager2)
        mViewPager2?.adapter = mData?.let { MyPagerAdapter(mData!!) }
    }

    class MyPagerAdapter(var mData: MutableList<String>) :
        RecyclerView.Adapter<MyPagerAdapter.MyViewHolder>() {

        class MyViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
            var iv: ImageView = itemView.findViewById<ImageView>(R.id.cover)
        }

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
            var view =
                LayoutInflater.from(parent.context).inflate(R.layout.item_pager, parent, false)
            return MyViewHolder(view)
        }

        override fun getItemCount(): Int {
            return Int.MAX_VALUE

        }

        override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
            val realPosition = position % mData.size
            val imgUrl = mData[realPosition]
            Glide.with(holder.iv.context)
                .load(imgUrl)
                .centerCrop()
                .into(holder.iv)
        }


    }

}
